package com.sun.communit;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockConminucate {
    public static void main(String[] args) {
        CalculateNum calculateNum = new CalculateNum();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    calculateNum.add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"AA").start();


        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    calculateNum.desc();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"BB").start();

    }
}

class CalculateNum {
    int initNum = 0;
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    //加数
    public void add() throws InterruptedException {
        try {
            lock.lock();
            while (initNum != 0) {
                condition.await();
            }
            initNum++;
            System.out.println(Thread.currentThread().getName() + ":" + initNum);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void desc() throws InterruptedException {
        try {
            lock.lock();
            while (initNum != 1) {
                condition.await();
            }
            initNum--;
            System.out.println(Thread.currentThread().getName() + ":" + initNum);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

